package com.detrum.detrumdx.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.detrum.ShareSettingActivity;
import com.detrum.base.BaseFinal;
import com.detrum.bean.FileBean;
import com.detrum.bean.FileBeanAll;
import com.detrum.bean.ShareBean;
import com.detrum.bean.ViewPagerItem;
import com.detrum.detrumdx.R;
import com.detrum.detrumdx.activity.MainActivity;
import com.detrum.detrumdx.adapter.LocalRefreshAdapter;
import com.detrum.myijkplayer.activities.VideoActivity;
import com.detrum.sportcamera.BigImageActivity;
import com.detrum.sqlite.SqliteDeviceOperate;
import com.detrum.sqlite.SqliteMediaOperation;
import com.detrum.sqlite.SqliteShareOperate;
import com.detrum.swipe.BaseRecyclerAdapter;
import com.detrum.swipe.OnLoadMoreListener;
import com.detrum.swipe.OnRefreshListener;
import com.detrum.swipe.SuperRefreshRecyclerView;
import com.detrum.utils.LogUtils;
import com.detrum.utils.MyMethod;
import com.detrum.utils.NfsUtil;
import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MediaFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MediaFragment extends Fragment implements View.OnClickListener, OnRefreshListener, OnLoadMoreListener,
        BaseRecyclerAdapter.OnItemLongClickListener,BaseRecyclerAdapter.OnItemClickListener
        {

    private OnFragmentInteractionListener mListener;

    private GridLayoutManager gridLayoutManager;
    private MainActivity parentActivity;
    private SuperRefreshRecyclerView refresh_view;
    private LocalRefreshAdapter localRefreshAdapter;



    private boolean isEdit;
    private LinearLayout bottom_local;
    private TextView selectAll_local, delete_local, cancel_local, noFiles_tv, share_tv;
    private boolean isSelectAll;

    private int localPage = 1;
    private ArrayList<FileBean> list_bean;
    private ArrayList<Uri> uris;
    public int isLocal = 0;

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 10) {
                refresh_view.setRefreshing(false);
                localRefreshAdapter = new LocalRefreshAdapter(list_bean, parentActivity);
                refresh_view.setAdapter(localRefreshAdapter);
                localRefreshAdapter.setOnItemClickListener(MediaFragment.this);
                localRefreshAdapter.setOnItemLongClickListener(MediaFragment.this);
                refresh_view.showData();
                LogUtils.e("setAdapter complete");
            } else if (msg.what == 11) {
                refresh_view.setRefreshing(false);
                localRefreshAdapter.notifyDataSetChanged();
            } else if(msg.what == 1){
                refresh_view.setRefreshing(false);
                localRefreshAdapter.notifyDataSetChanged();
            }else if (msg.what == 2) {
                refresh_view.setLoadingMore(false);
                localRefreshAdapter.notifyDataSetChanged();
            } else if (msg.what == 31) {
                MyMethod.ShowShareDialog2(parentActivity, shareList, uris);
            }
        }
    };

    public static MediaFragment newInstance() {
        MediaFragment fragment = new MediaFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_media, container, false);
        initView(view);
        return view;
    }

    public void onButtonPressed() {
        cancelBottom();
    }

    public void onBackDeviceList() {
        LoadDevice(11);
    }

    private void LoadDevice(final int flag) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (list_bean != null) {
                    list_bean.clear();
                } else {
                    list_bean = new ArrayList<>();
                }
                List<ViewPagerItem> list = SqliteDeviceOperate.getInstance(parentActivity).SelectAll();
                if (list != null && list.size() != 0) {
                    for (int i = 0; i < list.size(); i++) {
                        FileBean fileBean = new FileBean();
                        fileBean.setFileName(list.get(i).getName());
                        list_bean.add(fileBean);
                    }
                    isLocal = 0;
                    mListener.onLocal(isLocal);
                    handler.sendEmptyMessage(flag);
                }
            }
        }).start();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        parentActivity = (MainActivity) context;
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
        LogUtils.i("MediaFragment onAttach");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        LogUtils.i("MediaFragment onDetach");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (list_bean == null) {
            list_bean = new ArrayList<>();
        }
        if (BaseFinal.MediaFragmentRequest) {
            LoadDevice(10);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (deleteTask != null) {
            deleteTask.Stop();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.i("MediaFragment onDestroy");
    }

    private void LoadIWT() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (list_bean != null) {
                    list_bean.clear();
                } else {
                    list_bean = new ArrayList<>();
                }
                list_bean.addAll(SqliteMediaOperation.getInstence(parentActivity).SelectLocal(localPage, isLocal));
                LogUtils.e("LoadIWT = " + list_bean.size());
                handler.sendEmptyMessage(11);
            }
        }).start();
    }

    private void LoadDCAM() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (list_bean != null) {
                    list_bean.clear();
                } else {
                    list_bean = new ArrayList<>();
                }
                list_bean.addAll(SqliteMediaOperation.getInstence(parentActivity).SelectLocal(localPage, isLocal));
                LogUtils.e("LoadDCAM = " + list_bean.size());
                handler.sendEmptyMessage(11);
            }
        }).start();
    }

    private void initView(View view) {
        bottom_local = view.findViewById(R.id.bottom_local);
        selectAll_local = view.findViewById(R.id.selectAll_local);
        delete_local = view.findViewById(R.id.delete_local);
        cancel_local = view.findViewById(R.id.cancel_local);
        noFiles_tv = view.findViewById(R.id.noFiles_tv);
        share_tv = view.findViewById(R.id.share_tv);
        selectAll_local.setOnClickListener(this);
        delete_local.setOnClickListener(this);
        cancel_local.setOnClickListener(this);
        share_tv.setOnClickListener(this);

        gridLayoutManager = new GridLayoutManager(parentActivity, 2);
        refresh_view = view.findViewById(R.id.refresh_view);
        refresh_view.init(gridLayoutManager, this, this);
        refresh_view.setRefreshEnabled(true);
        refresh_view.setLoadingMoreEnable(true);
    }

    private void cancelBottom() {
        isEdit = false;
        isSelectAll = false;
        bottom_local.setVisibility(View.GONE);
        localRefreshAdapter.setEdit(isEdit);
        localRefreshAdapter.notifyDataSetChanged();
        mListener.onEdit(isEdit);
    }

    DeleteTask deleteTask;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel_local:
                cancelBottom();
                break;
            case R.id.delete_local:
                ArrayList<FileBean> arrayList = new ArrayList<>();
                for (int i = 0; i < list_bean.size(); i++) {
                    if (list_bean.get(i).isSelect()) {
                        arrayList.add(list_bean.get(i));
                    }
                }
                if (arrayList.size() == 0) {
                    cancelBottom();
                    return;
                }
                FileBean[] fileBeans = new FileBean[arrayList.size()];
                fileBeans = arrayList.toArray(fileBeans);
                deleteTask = new DeleteTask();
                deleteTask.execute(fileBeans);
                if (isSelectAll) {
                    isSelectAll = false;
                    selectAll_local.setText(R.string.all);
                }
                break;
            case R.id.selectAll_local:
                if (isSelectAll) {
                    isSelectAll = false;
                    selectAll_local.setText(R.string.all);
                    for (int i = 0; i < list_bean.size(); i++) {
                        list_bean.get(i).setSelect(false);
                    }
                } else {
                    isSelectAll = true;
                    selectAll_local.setText(R.string.noall);
                    for (int i = 0; i < list_bean.size(); i++) {
                        list_bean.get(i).setSelect(true);
                    }
                }
                localRefreshAdapter.notifyDataSetChanged();
                break;
            case R.id.share_tv:
                if (uris == null) {
                    uris = new ArrayList<>();
                } else {
                    uris.clear();
                }
                if (isSelectAll) {
                    for (int i = 0; i < list_bean.size(); i++) {
                        if (list_bean.get(i).getFileName().endsWith(".jpg")) {
                            Uri uri = Uri.fromFile(new File(list_bean.get(i).getCachePath()));
                            uris.add(uri);
                        }
                    }
                } else {
                    for (int i = 0; i < list_bean.size(); i++) {
                        if (list_bean.get(i).isSelect()) {
                            if (list_bean.get(i).getFileName().endsWith(".jpg")) {
                                Uri uri = Uri.fromFile(new File(list_bean.get(i).getCachePath()));
                                uris.add(uri);
                            }
                        }
                    }
                }
                cancelBottom();
                if (uris != null && uris.size() != 0) {
                    getShareList();
                }else{
                    MyMethod.ShowDialog(getActivity(),R.string.no_share);
                }
                break;
        }
    }

    PackageManager pm;
    List<ResolveInfo> list;
    List<ShareBean> shareList;

    private void getShareList() {
        pm = parentActivity.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        list = pm.queryIntentActivities(intent, 0);
        new Thread(new Runnable() {
            @Override
            public void run() {
                shareList = SqliteShareOperate.getInstence(parentActivity).SelectAll(1);
                if (shareList == null) {
                    parentActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MyMethod.toActivity(parentActivity, ShareSettingActivity.class);
                        }
                    });
                    return;
                }
                for (int i = 0; i < shareList.size(); i++) {
                    for (int j = 0; j < list.size(); j++) {
                        if (shareList.get(i).getName().equals(list.get(j).loadLabel(pm).toString())) {
                            shareList.get(i).setIcon(list.get(j).loadIcon(pm));
                            break;
                        }
                    }
                }
                handler.sendEmptyMessage(31);
            }
        }).start();
    }

    @Override
    public void onRefresh() {
        localPage = 1;
        if (isLocal == 0) {
            refresh_view.setRefreshing(false);
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (list_bean != null) {
                    list_bean.clear();
                }
                list_bean.addAll(SqliteMediaOperation.getInstence(parentActivity).SelectLocal(localPage, isLocal));
                handler.sendEmptyMessage(1);
            }
        }).start();
    }

    @Override
    public void onLoadMore() {
        if (isLocal == 0) {
            refresh_view.setLoadingMore(false);
            return;
        }
        localPage++;
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<FileBean> list = SqliteMediaOperation.getInstence(parentActivity).SelectLocal(localPage, isLocal);
                if (list != null && list.size() != 0) {
                    list_bean.addAll(list);
                    handler.sendEmptyMessage(2);
                } else {
                    refresh_view.setLoadingMore(false);
                }

            }
        }).start();
    }

    @Override
    public void onItemClick(View view,int position,long id) {
        if (list_bean == null || list_bean.size() == 0) {
            LogUtils.e("beanList is null");
            return;
        }
        if (isEdit) {
            boolean select = list_bean.get(position).isSelect();
            if (select) {
                list_bean.get(position).setSelect(false);
            } else {
                list_bean.get(position).setSelect(true);
            }
            localRefreshAdapter.notifyItemChanged(position);
            return;
        }
        String name = list_bean.get(position).getFileName();
        // TODO: 2018/5/4 wifi模块相关
        boolean isImage = NfsUtil.isImageFile(name);
        boolean isVideo = NfsUtil.isVideoFile(name);
        LogUtils.i("name = " + name);
        int flag = 0;
        if (isImage) {
            ArrayList<FileBean> list = new ArrayList<>();
            LogUtils.i("list_bean size = " + list_bean.size());
            for (int i = 0; i < list_bean.size(); i++) {
                if (NfsUtil.isImageFile(list_bean.get(i).getFileName()) && list_bean.get(i).getCachePath() != null) {
                    list.add(list_bean.get(i));
                    if (i == position) {
                        flag = list.size() - 1;
                    }
                }
            }
            LogUtils.i("list size = " + list.size());
            FileBeanAll all = new FileBeanAll();
            all.setBeanList(list);
            all.setFlag(2);
            Gson gson = new Gson();
            String json = gson.toJson(all);
            // TODO: 2018/5/4 wifi模块相关
            Intent intent1 = new Intent(parentActivity, BigImageActivity.class);
            intent1.putExtra("json", json);
            intent1.putExtra("position", flag);
            parentActivity.startActivityForResult(intent1, BaseFinal.MediaFragment);
        } else if (isVideo) {
            Gson gson = new Gson();
            String json = gson.toJson(list_bean.get(position));
            // TODO: 2018/5/4 wifi模块相关
            Intent intent = new Intent(parentActivity, VideoActivity.class);
            intent.putExtra("json", json);
            parentActivity.startActivityForResult(intent, BaseFinal.MediaFragment);
        } else if (name.equals("IWT-AGS58")) {
            isLocal = 2;
            LoadIWT();
            mListener.onLocal(isLocal);
        } else if (name.equals("DCAM-H")) {
            isLocal = 1;
            LoadDCAM();
            mListener.onLocal(isLocal);
        }
    }

    @Override
    public boolean onItemLongClick(View view,int position,long id) {
        LogUtils.i("localRefreshAdapter onItemLongClick " + position);
        if (isLocal == 0) {
            return false;
        }
        isEdit = true;
        localRefreshAdapter.setEdit(true);
        localRefreshAdapter.notifyDataSetChanged();
        bottom_local.setVisibility(View.VISIBLE);
        mListener.onEdit(isEdit);
        return false;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);

        void onEdit(boolean isEdit);

        void onLocal(int Local);
    }

    class DeleteTask extends AsyncTask<FileBean, String, Void> {
        private boolean isStop;

        public void Stop() {
            isStop = true;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            onRefresh();
            bottom_local.setVisibility(View.GONE);
            isEdit = false;
            localRefreshAdapter.setEdit(isEdit);
            mListener.onEdit(isEdit);
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected Void doInBackground(FileBean... fileBeans) {
            if (fileBeans != null && fileBeans.length != 0) {
                int length = fileBeans.length;
                LogUtils.e("length = " + length);
                for (int i = 0; i < length; i++) {
                    LogUtils.e("getNfsPath = " + fileBeans[i].getNfsPath());
                    if (isStop) {
                        break;
                    }
                    String fileName = fileBeans[i].getFileName();
                    int[] flags = SqliteMediaOperation.getInstence(parentActivity).getFlags(fileName);
                    if (flags[1] == 0 || flags[0] == 10) {
                        String cacheName = SqliteMediaOperation.getInstence(parentActivity).getFilePath(fileName);
                        if (cacheName == null || cacheName.length() == 0) {
                            continue;
                        }
                        File file = new File(cacheName);
                        if (file != null) {
                            file.delete();
                        }
                        SqliteMediaOperation.getInstence(parentActivity).DeleteItem(fileName);
                    } else if (flags[1] == 1) {
                        SqliteMediaOperation.getInstence(parentActivity).UpdataItemLocal(0, fileName);
                    }
                    publishProgress(fileBeans[i].getFileName() + "----success");
                }
            }
            return null;
        }
    }
}
